package com.flong.juc.charter2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:liangjl
 * @Date: 2020/7/13-10:25
 * @Eamil:jilongliang@sina.com
 * @Description:
 * 关于Lock与synchronized关键字在锁的处理行的重要差别
 * 1、锁的获取方式，前者是通过程序代码方式由开发这手工获取，后者是通过JVM来获取(无需开发者干预)
 * 2、具体实现方式：前者是通过Java代码的方式来实现，后者是通过JVM底层来实现(无需开发者关注)
 * 3、锁的释放方式：前者务必通过unlock方法在finally块中手工释放，后者是通过JVM来释放(无需开发者关注)
 * 4、锁的具体类型：前者提供了多种，如：公平锁，非公平锁，后者与前者均提供了可重入锁
 */
public class Lock1 {

    //ReentrantLock可重入锁
    private Lock lock = new ReentrantLock();

    public void method1() {
        lock.lock();
        try {

            System.out.println("method1");
        } finally {
            //注释这行代码就一直执行method1方法，而程序一直处于在运行状态
           lock.unlock();
        }
    }

    public void method2() {
        lock.lock();
        try {
            System.out.println("method2");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Lock1 lock1 = new Lock1();
        Thread t1 = new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                lock1.method1();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                lock1.method2();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
    }
}
